package com.atguigu.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Author zhaolie
 * @Date 2020/12/5 9:59 下午
 * @Version 1.0
 * @Description OSS服务
 */

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 上传文件流。
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            // 获取文件名称
            String filename = file.getOriginalFilename();

            // 1.在文件名称中添加随机唯一值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");

            // 2.文件按日期进行分类
            String date = new DateTime().toString("yyyy/MM/dd");
            filename = date + "/" + uuid + filename;
            ossClient.putObject(bucketName, filename, inputStream);
            StringBuffer url = new StringBuffer();
            // https://zl-2020.oss-cn-shanghai.aliyuncs.com/343EB272-83A7-44C2-B265-9D90F0C415DA.jpeg
            url.append("https://").append(bucketName).append(".").append(endpoint).append("/").append(filename);
            return url.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
    }
}
